<?php
namespace Home\Controller;
use Think\Controller;
use App\Controller\BaseController;
class GoodsCartController extends BaseController {

    public function _initialize(){
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if(empty($midiuser)){
            $this->redirect('Home/Index/login');
        }
        $this->assign('midiuser',$midiuser);
    }
    
    /**
     * 购物车相关操作
     *
     */
    public function cart_list()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if(empty($midiuser)){
            $this->redirect('Home/Index/login');
        }
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        $data_list = M('shoppingcart')
            ->where(['shoppingcart_user_id'=>$midiuser['user_id']])
            ->find();
        $new_data = [];
        if(!empty($data_list['shoppingcart_details'])){
            $return = setGoodsDetailData($data_list['shoppingcart_details']);
            //查询所有商品信息
            $data_list = M('goods')
                ->field('goods_id,goods_name,goods_pic,goods_price,goods_display,goods_sell_out')
                ->where([
                    'goods_id'=>['in',$return['goods_id_arr']],
                ])
                ->select();
            if(!empty($data_list)){
                foreach ($return['data'] as $key => $val) {
                    foreach ($data_list as $k => $v) {
                        if($val['goods_id'] == $v['goods_id']){
                            $v['goods_num'] = $val['goods_num'];
                            $v['total_price'] = $v['goods_price'] * $v['goods_num'];
                            $new_data[] = $v;
                            unset($return['data'][$key]);
                            unset($data_list[$k]);
                        }
                    }
                }
            }
        }
//        var_dump($new_data);
        $this->assign('data_list',$new_data);
        $this->display();
    }

    //删除购物车中商品 多个商品中间用逗号隔开
    public function del_goods_cart(){
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if(empty($midiuser)){
            $this->redirect('Home/Index/login');
        }
        $id = trim(I('ids'));
        $id_arr = explode(',',$id);
        $cart_model = M('shoppingcart');
        $info = $cart_model
            ->field('shoppingcart_totalprice',true)
            ->where(['shoppingcart_user_id'=>$midiuser['user_id']])
            ->find();
        if(!empty($info['shoppingcart_details'])){
            $new_arr = explode(',',$info['shoppingcart_details']);
            if(count($id_arr) > 1){
                foreach ($new_arr as $key => $val) {
                    foreach ($id_arr as $k => $v) {
                        if(trim(strstr($val,':',true)) == $v){
                            unset($id_arr[$k]);
                            unset($new_arr[$key]);
                        }
                    }
                }
            }else{
                foreach ($new_arr as $key => $val) {
                    if(trim(strstr($val,':',true)) == $id_arr[0]){
                        unset($new_arr[$key]);
                    }
                }
            }
            $info['shoppingcart_details'] = implode(',',$new_arr);
            $res = $cart_model->save($info);
            if($res){
                $this->ajaxReturn(['status'=>1,'msg'=>'删除成功！']);
            }else{
                $this->ajaxReturn(['status'=>3,'msg'=>'操作失败，请刷新重试！']);
            }
        }else{
            $this->ajaxReturn(['status'=>2,'msg'=>'操作失败，请刷新重试！']);
        }
    }



    //加入购物车
    public function add_shoppingcart(){
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (empty($midiuser)) {
            $this->redirect('Home/Index/login');
        }
        $goods_id = I('id');
        $goods_num = I('num',1,'intval');
        //判断商品是否售罄
        if(!$this->has_goods($goods_id)){
            $this->ajaxReturn(['status'=>2,'msg'=>'商品已售罄！']);
            return;
        }
        //查询是否有购物车数据记录，以作处理
        $cart_model = M('shoppingcart');
        $find_res = $cart_model->where(['shoppingcart_user_id'=>$midiuser['user_id']])->find();
        //第一次加入购物车
        if(empty($find_res)){
            $str = $goods_id.':'.$goods_num;
            $res = $cart_model->add(array(
                    'shoppingcart_user_id'=>$midiuser['user_id'],
                    'shoppingcart_details'=>$str,
                )
            );
        }else if(!empty($find_res['shoppingcart_details'])){
            //购物车中已经有数据，执行更新操作
            $goods_cart_data = explode(',',$find_res['shoppingcart_details']);
            $new_goods_id_array = [];
            foreach ($goods_cart_data as $k => &$v) {
                $new_goods_id_array[] = trim(strstr($v,':',true),':');
            }
            if(in_array($goods_id,$new_goods_id_array)){
                foreach ($goods_cart_data as $key => &$val) {
                    if($goods_id == trim(strstr($val,':',true),':')){
                        $val = $goods_id.':'.(trim(strstr($val,':'),':') + $goods_num);
                    }
                }
                $find_res['shoppingcart_details'] = implode(',',$goods_cart_data);
            }else{
                $find_res['shoppingcart_details'] =
                    $goods_id.':'.$goods_num.','.$find_res['shoppingcart_details'];
            }
            $res = $cart_model->save($find_res);
        }else if(empty($find_res['shoppingcart_details'])){
            $str = $goods_id.':'.$goods_num;
            $res = $cart_model->save(array(
                    'shoppingcart_id'=>$find_res['shoppingcart_id'],
                    'shoppingcart_details'=>$str,
                )
            );
        }
        if($res){
            $this->ajaxReturn(['status'=>1,'msg'=>'加入成功！']);
        }else{
            $this->ajaxReturn(['status'=>3,'msg'=>'加入失败,请刷新重试！']);
        }
    }

    //判断商品是否已售罄
    public function has_goods($id)
    {
        $res = M('goods')
            ->field('goods_sell_out,goods_display')
            ->find($id);
        if(!empty($res) && $res['goods_sell_out'] == 1 && $res['goods_display'] == 1){
            return true;
        }else{
            return false;
        }
    }
    
}